package kr.ac.kaist.idb.snql.manager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import kr.ac.kaist.idb.csnql.clause.SNQLQueryPacket;
import kr.ac.kaist.idb.csnql.lib.Base64Coder;
import kr.ac.kaist.idb.snql.networkmetadata.NetworkMetadata;

public class TransmissionManager {
	public void sendPacket(List<NetworkMetadata> networkMetadataList, SNQLQueryPacket snqlQueryPacket) throws IOException
	{
		for (NetworkMetadata networkMetadata: networkMetadataList)
		{
			sendPacket(networkMetadata, snqlQueryPacket);
		}
	}

	public void sendPacket(NetworkMetadata networkMetadata, SNQLQueryPacket snqlQueryPacket) throws IOException
	{
		String queryMessage = snqlQueryPacket.marshall();
	}

	/**
	 * @brief Marshalls the Event into a string and encodes it using Base64 coding
	 * @return A string that is Base64 encoded containing the marshalled event
	 * @throws IOException
	 */
	public String marshall(Object object) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(baos);
		out.writeObject(object);
		out.close();
		byte[] marshalledEvent = baos.toByteArray();
		String base64EndocdedMarshalledEvent = Base64Coder.encodeLines(marshalledEvent);
		return(base64EndocdedMarshalledEvent);
	}

	/**
	 * @brief Decodes the string from Base64 coding and unmarshalls the event and returns it
	 * @param base64EncodedMarshalledEvent A String that is encoded using Base64 coding and contains
	 *        a marshalled event
	 * @return The event object that was marshalled and encoded in the argument string 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static NetworkMetadata unmarshall(String base64EncodedMarshalledEvent)
			throws IOException, ClassNotFoundException {
		byte[] marshalledEvent = Base64Coder.decodeLines(base64EncodedMarshalledEvent);
		ObjectInputStream ois =
				new ObjectInputStream(new ByteArrayInputStream(marshalledEvent));
		NetworkMetadata o = (NetworkMetadata)ois.readObject();
		ois.close();
		return(o);
	}
}
